﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using BLToolkit.Mapping;
using BLToolkit.DataAccess;

namespace DAL
{
    public static class ReflectionExtensions
    {
        // Fields
        private static readonly Hashtable _keyList = new Hashtable();

        // Methods
        public static string GetFirstKey<T>(this Type value) where T : class
        {
            MemberMapper[] mmList = value.GetKeyFieldList<T>();
            return ((mmList.Length == 0) ? null : mmList[0].Name);
        }

        public static MemberMapper[] GetKeyFieldList<T>(this Type value) where T : class
        {
            string key = value.FullName;
            MemberMapper[] mmList = (MemberMapper[])_keyList[key];
            if (mmList == null)
            {
                List<MemberMapper> list = new List<MemberMapper>();
                foreach (MemberMapper mm in ObjectMapper<T>.Instance)
                {
                    if (!mm.MapMemberInfo.SqlIgnore)
                    {
                        PrimaryKeyAttribute attr = mm.MapMemberInfo.MemberAccessor.GetAttribute<PrimaryKeyAttribute>();
                        if (attr != null)
                        {
                            list.Insert(0, mm);
                        }
                    }
                }
                mmList = list.ToArray();
                _keyList[key] = mmList;
            }
            return mmList;
        }

    }
}
